<template>
  <q-page class="q-pa-md">
    <div class="q-pb-md text-h5">
      {{ pageTitle }}
      <span class="text-subtitle1">{{ pageSubTitle }}</span>
    </div>
    <div class="q-pa-sm shadow-2 row">
      <div class="q-gutter-sm">
        <q-btn @click="detailNav.goBackToList" color="primary" icon="arrow_back" outline title="返回" />
        <q-btn :disable="loadingState" :loading="loadingState" @click="loadModelData" color="primary" dense
          icon="refresh" outline title="刷新" v-if="isViewOrEditMode" />
      </div>
    </div>
    <div class="shadow-2 q-mt-md">
      <q-tabs active-color="primary" align="left" dense indicator-color="primary" v-model="showingTabPanel">
        <q-tab :label="'移库单' + pageSubTitle" name="invMove" />
        <q-tab label="移库单明细" name="invMoveLineList" v-if="isViewOrEditMode" />
        <q-tab :label="ldsModelData.tabTitle.value" name="invMoveLineDetail"
          v-if="ldsModelData.isLineTabDisp.value" />
        <q-tab label="附件" name="accessory" v-if="isViewOrEditMode" />
      </q-tabs>
      <q-separator />
      <q-tab-panels :keep-alive-include="['invMove','invMoveLineList','accessory']" keep-alive
        v-model="showingTabPanel">
        <q-tab-panel class="q-pa-sm" name="invMove">
          <div class="q-gutter-sm">
            <q-btn :disable="loadingState" @click="detailNav.goEditMode()" color="primary" icon="edit" label="编辑"
              v-if="isViewMode && fx.hasModifyRight('Wms.Inv.InvMove.Edit')" />
            <q-btn :disable="loadingState" @click="deleteInvMove" color="red" icon="delete_outline" label="删除"
              v-if="isViewMode && fx.hasModifyRight('Wms.Inv.InvMove.Edit') &&
              ( $d.form.moveState === '0' || $d.form.moveState === '1' || $d.form.moveState === '5' )" />
            <q-btn :disable="loadingState" @click="checkFn" color="primary" icon="how_to_reg" label="审核"
              v-if="isViewMode && fx.hasModifyRight('Wms.Inv.InvMove.Confirm')
                && $d.form.moveState < 1 && moveDetailHasLines" />
            <q-btn @click="cancelFn" color="red" icon="block" label="取消移库单"
              v-if="isViewMode && fx.hasModifyRight('Wms.Inv.InvMove.Cancel') && $d.form.moveState < 5"
              :disable="loadingState" />
            <q-btn :disable="loadingState" :loading="submitingState" color="primary" label="确定"
              v-if="isCreateOrEditMode" @click="doSubmit" />
            <q-btn :disable="submitingState || loadingState" @click="detailNav.cancelSubmit()" color="primary"
              label="取消" outline
              v-if="isEditMode" />
            <q-btn :disable="loadingState" @click="printMoveInv" color="primary" icon="eva-printer"
              label="打印移库单" v-if="isViewMode && fx.hasModifyRight('Wms.Inv.InvMove.Print')" />
<!--            <q-btn :disable="loadingState" @click="SendMoveTaskToWcs" color="primary"-->
<!--              label="下发移库任务" v-if="isViewMode && fx.hasModifyRight('Wms.Inv.Inventory.SendMoveTaskToWcs') && $d.form.moveState === '1'" />-->
          </div>
          <q-banner class="text-white bg-red q-mt-sm" dense inline-actions v-if="serverErrorMessage">
            {{ serverErrorMessage }}
            <template v-slot:action>
              <q-btn @click="serverErrorMessage=''" dense flat icon="close" size="sm" />
            </template>
          </q-banner>
          <div class="q-mt-sm">
            <form-field-group :model-with-create-update="$d.form" model-id="moveId" title="主要信息">
              <div class="q-pa-sm">
                <div class="row q-col-gutter-sm">
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <q-icon color="red" name="fas fa-asterisk" size="10px" />
                    <span>仓库</span>
                    <simple-filter-select :error="v$.whId.$error" :error-message="e$(v$.whId.$errors)"
                      :options="$d.whDropdownList" v-model="$d.form.whId" @update:model-value="onWhChanged"
                      option-label="whName" option-value="whId" auto-select-single-option
                      :readonly="isViewMode || $d.form.moveState > 1 || moveDetailHasLines" :use-filter="false"
                      />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <q-icon color="red" name="fas fa-asterisk" size="10px" />
                    <span>货主</span>
                    <simple-filter-select auto-select-single-option :error="v$.storerId.$error"
                      :error-message="e$(v$.storerId.$errors)" :options="$d.storerDropdownList"
                      :readonly="isViewMode || $d.form.moveState > 1 || moveDetailHasLines"
                      option-label="abbrName" option-value="mfId" :use-filter="false" v-model="$d.form.storerId" />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <q-icon color="red" name="fas fa-asterisk" size="10px" />
                    <span>来源储区</span>
                    <simple-filter-select :error="v$.fZoneId.$error" :error-message="e$(v$.fZoneId.$errors)"
                      :options="$d.zoneDropdownList"
                      option-label="zoneName" option-value="zoneId" :use-filter="false" v-model="$d.form.fZoneId"
                      :readonly="isViewMode || $d.form.moveState > 1 || moveDetailHasLines" />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <q-icon color="red" name="fas fa-asterisk" size="10px" />
                    <span>目的储区</span>
                    <simple-filter-select :error="v$.tZoneId.$error" :error-message="e$(v$.tZoneId.$errors)"
                      :options="$d.zoneDropdownList"
                      option-label="zoneName" option-value="zoneId" :use-filter="false" v-model="$d.form.tZoneId"
                      :readonly="isViewMode || $d.form.moveState > 1 || moveDetailHasLines" />
                  </div>
                </div>
                <div class="row q-col-gutter-sm q-pt-sm">
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <q-icon color="red" name="fas fa-asterisk" size="10px" />
                    <span>计划移库日期</span>
                    <div class="col-8">
                      <easy-input v-model="$d.form.expectedDt" :error="v$.expectedDt.$error"
                        :error-message="e$(v$.expectedDt.$errors)" :hide-bottom-space="true" :append-icon-show="true"
                        :readonly="isViewMode" clearble :use-date-picker="!isViewMode">
                      </easy-input>
                    </div>
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3" v-if="isViewOrEditMode">
                    <span>实际移库日期</span>
                    <q-input :hide-bottom-space="true" clearable dense :maxlength="40" outlined readonly square
                      stack-label :model-value="fx.fmt.dtFmtDateOnly(String($d.form.moveDt))"></q-input>
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <q-icon color="red" name="fas fa-asterisk" size="10px" />
                    <span>移库类型</span>
                    <simple-filter-select :options="$d.docTypeDropdownList"
                      option-label="codeName1" option-value="codeValue" :readonly="isViewMode" :use-filter="false"
                      v-model="$d.form.docType" :error="v$.docType.$error"
                      :error-message="e$(v$.docType.$errors)" />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3" v-if="!isCreateMode">
                    <span>状态</span>
                    <simple-filter-select :options="$d.moveStateDropdownList" v-model="$d.form.moveState"
                      readonly :use-filter="false" />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <span>供应商</span>
                    <simple-filter-select :options="supplierList" v-model="$d.form.mhlInvMoveExt.supplier"
                      :readonly="isViewMode" :use-filter="false" />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <span>楼层</span>
                    <easy-input v-model="$d.form.mhlInvMoveExt.floorNo" :readonly="isViewMode"></easy-input>
                  </div>
                  <div class="col-12">
                    <q-icon color="red" name="fas fa-asterisk" size="10px" />
                    <span>移库原因</span>
                    <q-input :error="v$.reason.$error" :error-message="e$(v$.reason.$errors)"
                      :dense="true" :hide-bottom-space="true" :readonly="isViewMode" autogrow :maxlength="300"
                      outlined square stack-label type="textarea" v-model="$d.form.reason">
                    </q-input>
                  </div>
                </div>
              </div>
            </form-field-group>
            <form-field-group class="q-mt-md" title="其他信息">
              <div class="q-pa-sm">
                <div class="row q-col-gutter-sm q-pb-sm">
                  <div class="col-12">
                    <span>描述</span>
                    <q-input :dense="true" :hide-bottom-space="true" :readonly="isViewMode" autogrow :maxlength="300"
                      outlined square stack-label type="textarea" v-model="$d.form.descriptions">
                    </q-input>
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3" v-if="isViewMode">
                    <span>审核时间</span>
                    <q-input :hide-bottom-space="true" readonly dense outlined square stack-label
                      v-model="$d.form.confirmDt">
                    </q-input>
                  </div>
                  <div class="col-12 col-sm-6 col-md-4 col-lg-3" v-if="isViewMode">
                    <span>审核人员</span>
                    <q-input :hide-bottom-space="true" readonly dense outlined square stack-label
                      v-model="$d.form.confirmP">
                    </q-input>
                  </div>
                </div>
              </div>
            </form-field-group>
          </div>
        </q-tab-panel>
        <q-tab-panel class="q-pa-none" name="invMoveLineList">
          <q-table :columns="columnsInfoInvMoveLine" :rows="$d.form.mhlLines" row-key="moveLineId" separator="cell"
            :loading="loadingState" color="primary" dense flat v-model:selected="$d.selectedInvMoveLines"
            selection="multiple" v-model:pagination="$d.paginationMoveLine"
            :hide-pagination="true" @row-dblclick="(evt,row)=>{ldhModelData.lineDetailNav.goViewLine(row.moveLineId)}"
            :visible-columns="$d.visibleColumnsInvMoveLine">
            <template v-slot:top="props">
              <div class="q-gutter-sm">
                <q-btn :disable="loadingState" @click="createInvMoveLine" color="primary" icon="add" label="新建明细"
                  v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit') && ($d.form.moveState === '0' || $d.form.moveState === '1')" />
                <q-btn :disable="$d.selectedInvMoveLines.length===0 || loadingState"
                  @click="onDeleteInvMoveLines" color="red" icon="delete_outline" label="删除明细"
                  v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit') && ($d.form.moveState === '0' || $d.form.moveState === '1')" />
              </div>
              <q-space />
              <table-col-options-cfg v-model:table-columns="columnsInfoInvMoveLine"
                v-model:visible-columns="$d.visibleColumnsInvMoveLine"
                @update-col-options-for-save="(optToSave)=>dlAssist.saveDetailColOptions('invMoveLineList',optToSave)"
                class="q-ml-sm">
              </table-col-options-cfg>
              <q-btn :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" @click="props.toggleFullscreen"
                class="q-ml-sm" dense flat />
            </template>
            <template v-slot:body-cell-operation="props">
              <q-td :props="props" auto-width>
                <q-btn :disable="loadingState"
                  @click="ldhModelData.lineDetailNav.goEditLine(props.row.moveLineId)" class="btn-in-row"
                  color="primary" dense label="编辑" v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit')" />
                <q-btn :disable="loadingState"
                  @click="ldhModelData.lineDetailNav.goViewLine( props.row.moveLineId)" class="btn-in-row q-ml-xs"
                  color="primary" dense label="查看" />
              </q-td>
            </template>
            <template v-slot:body-cell-isMoved="props">
              <q-td :props="props" auto-width>
                <q-badge :color="props.row.isMoved ? 'positive' : 'red' " :label="props.row.isMoved ? '已完成' : '未完成'" />
              </q-td>
            </template>
            <!--料号类型-->
            <template v-slot:body-cell-mfType="props">
              <q-td :props="props">
                {{ fx.fmt.fmtSkuType(props.row.mfType) }}
              </q-td>
            </template>
            <!--无数据提示-->
            <template v-slot:no-data>
              <span class="full-width text-center">
                <q-icon name="error_outline" /> 无数据
              </span>
            </template>
            <template v-slot:bottom>
              <paging-bar :loading-state="loadingState" :pageNo="$d.paginationMoveLine.page"
                :pageSize="$d.paginationMoveLine.rowsPerPage" :restrict-input-page-no="true"
                :show-refresh-button="false" :totalAmount="$d.form.mhlLines.length"
                @go-to-page="(pageNo)=>{$d.paginationMoveLine.page=pageNo}"
                @pagesize-changed="(pageSize)=>{$d.paginationMoveLine.rowsPerPage=pageSize;dlAssist.saveDetailPageSize('invMoveLineList',pageSize)}" />
            </template>
          </q-table>
        </q-tab-panel>
        <q-tab-panel class="q-pa-sm" name="invMoveLineDetail">
          <div class="q-gutter-sm">
            <q-btn @click="ldhModelData.lineDetailNav.backToListTab" color="primary" icon="close" outline
              title="关闭"
              v-if="ldsModelData.isLineViewMode.value" />
            <q-btn :disable="lineLoadingState" :loading="lineLoadingState"
              @click="loadLineModelData" color="primary" dense
              icon="refresh" outline title="刷新" v-if="ldsModelData.isLineViewOrEditMode.value" />
            <q-btn :disable="lineLoadingState"
              @click="ldhModelData.lineDetailNav.turnLineToEditMode()"
              color="primary" icon="edit" label="编辑"
              v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit') && ldsModelData.isLineViewMode.value" />
            <q-btn :disable="lineLoadingState"
              @click="onDeleteInvMoveLine(ldhModelData.lineDetailInfo.lineItemId)" color="red"
              icon="delete_outline"
              label="删除"
              v-if="fx.hasModifyRight('Wms.Inv.InvMove.Edit') && ldsModelData.isLineViewMode.value &&
              ldhModelData.lineDetailInfo.lineForm.isMoved === false" />
            <q-btn :loading="modelSubmittingState" @click="doSubmitInvMoveLine" color="primary"
              label="确定"
              v-if="ldsModelData.isLineCreateOrEditMode.value" />
            <q-btn :disable="modelSubmittingState" @click="ldhModelData.lineDetailNav.cancelLineSubmit"
              label="取消" outline
              v-if="ldsModelData.isLineCreateOrEditMode.value" color="primary" />
          </div>
          <q-banner class="text-white bg-red q-mt-sm" dense inline-actions v-if="serverErrorMessageModelData">
            {{ serverErrorMessageModelData }}
            <template v-slot:action>
              <q-btn @click="serverErrorMessageModelData=''" dense flat icon="close" size="sm" />
            </template>
          </q-banner>
          <form-field-group :model-with-create-update="ldhModelData.lineDetailInfo.lineForm" class="q-mt-sm"
            model-id="moveLineId" title="主要信息">
            <div class="q-pa-sm">
              <div class="row q-col-gutter-sm" v-if="ldsModelData.isLineViewMode.value">
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>移库完成</span>
                  <div class="bg-grey-3">
                    <q-checkbox :disable="isViewMode" class="full-width q-pa-xs" color="primary q-pa-xs" dense
                      v-model="ldhModelData.lineDetailInfo.lineForm.isMoved" readonly />
                  </div>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>移动日期</span>
                  <q-input :hide-bottom-space="true"
                    :model-value="fx.fmt.dtFmtFullWithMSec(ldhModelData.lineDetailInfo.lineForm.operateDt)" dense outlined
                    readonly square stack-label/>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>操作人</span>
                  <q-input :hide-bottom-space="true" :model-value="ldhModelData.lineDetailInfo.lineForm.operateP" dense
                    outlined readonly square stack-label/>
                </div>
              </div>
              <div class="row q-col-gutter-sm q-pt-sm">
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <q-icon color="red" name="fas fa-asterisk" size="10px" />
                  <span>库存ID</span>
                  <wm-inv-loc-selector :wh-id="$d.form.whId" :invLocId="ldhModelData.lineDetailInfo.lineForm.invLocId"
                    :readonly="ldsModelData.isLineViewMode.value || !($d.form.moveState === '0' || $d.form.moveState === '1')"
                    :wh-dropdown-list="$d.whDropdownList" :storer-dropdown-list="$d.storerDropdownList"
                    @inv-loc-selected="onInvLocSelected" :storer-id="$d.form.storerId"
                    v-model="ldhModelData.lineDetailInfo.lineForm.invLocId" no-error-icon
                    :error="v$model.invLocId.$error" :error-message="e$(v$model.invLocId.$errors)"
                    :zone-dropdown-list-by-wh-id="$d.zoneDropdownList" :zone-id="$d.form.fZoneId">
                  </wm-inv-loc-selector>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <q-icon color="red" name="fas fa-asterisk" size="10px" />
                  <span>移动数量</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.qty" dense outlined
                    :maxlength="40" square stack-label
                    :readonly="ldsModelData.isLineViewMode.value || !($d.form.moveState === '0' || $d.form.moveState === '1')"
                    :error="v$model.qty.$error" :error-message="e$(v$model.qty.$errors)" no-error-icon>
                    <template v-slot:append
                      v-if="!(ldsModelData.isLineViewMode.value || !($d.form.moveState === '0' || $d.form.moveState === '1'))
                      && ldhModelData.lineDetailInfo.lineForm.qtyAvailable">
                          <span class="text-caption text-black">
                            可用量:{{ ldhModelData.lineDetailInfo.lineForm.qtyAvailable }}
                          </span>
                    </template>
                  </q-input>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <q-icon color="red" name="fas fa-asterisk" size="10px" />
                  <span>目标储位</span>
                  <simple-filter-select :error="v$model.tLocId.$error" :error-message="e$(v$model.tLocId.$errors)"
                    :readonly="ldsModelData.isLineViewMode.value || !($d.form.moveState === '0' || $d.form.moveState === '1')"
                    option-label="loc" option-value="locId" v-model="ldhModelData.lineDetailInfo.lineForm.tLocId"
                    server-side-url="/wms/basic/loc/get-loc-simple-list" search-content-field="loc"
                    resp-data-field="locs" :req-params="{pageNo:1,pageSize:10,whId:$d.form.whId,zoneId:$d.form.tZoneId}"
                    :options="$d.locDropdownList" />
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <q-icon color="red" name="fas fa-asterisk" size="10px" />
                  <span>目标栈板</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.tLpn" dense outlined
                    :maxlength="40" square stack-label
                    :readonly="ldsModelData.isLineViewMode.value || !($d.form.moveState === '0' || $d.form.moveState === '1')"
                    :error="v$model.tLpn.$error" :error-message="e$(v$model.tLpn.$errors)" no-error-icon>
                  </q-input>
                </div>
              </div>
              <div class="row q-col-gutter-sm q-pt-sm">
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>料号</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.sku" dense outlined
                    readonly square stack-label/>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>品名</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.skuName" dense
                    outlined readonly square stack-label/>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>英文品</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.skuNameE" dense
                    outlined readonly square stack-label/>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>规格型号</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.spec" dense outlined
                    readonly square stack-label/>
                </div>
              </div>
              <div class="row q-col-gutter-sm q-pt-sm">
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>批号</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.lot" dense outlined
                    readonly square stack-label/>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>来源储位</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.fLoc" dense outlined
                    readonly square stack-label/>
                </div>
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                  <span>来源栈板</span>
                  <q-input :hide-bottom-space="true" v-model="ldhModelData.lineDetailInfo.lineForm.fLpn" dense outlined
                    readonly square stack-label/>
                </div>
                <div class="col-12">
                  <span>描述</span>
                  <q-input :hide-bottom-space="true" :readonly="ldsModelData.isLineViewMode.value" autogrow dense
                    :maxlength="300" outlined square stack-label type="textarea"
                    v-model="ldhModelData.lineDetailInfo.lineForm.descriptions"/>
                </div>
              </div>
            </div>
          </form-field-group>
        </q-tab-panel>
        <q-tab-panel class="q-pa-none" name="accessory" v-if="isViewOrEditMode">
          <accessory right-name-for-edit="Wms.Inv.InvMove.Edit" :storage-id="detailInfo.itemId"
            :delete-url="'/wms/inv/inventory/delete-inv-move-attachments/'+detailInfo.itemId"
            :recomment-url="'/wms/inv/inventory/recomment-inv-move-attachment/'+detailInfo.itemId"
            storage-class="wm-inv-move"
            upload-url="/wms/inv/inventory/upload-inv-move-attachments/"
            :enable-pack-download="props.enableAccessoryPackDownload">
          </accessory>
        </q-tab-panel>
      </q-tab-panels>
    </div>
  </q-page>
</template>
<script lang="ts">
export default {
  name: 'WmInvMoveStd'
}
</script>
<script lang="ts" setup>
import {useDetailHelper} from '@njt/foundation/hooks/detailHelper'
import {useTitleHelper} from '@njt/foundation/hooks/titleHelper'
import {computed, reactive, ref} from 'vue'
import useVuelidate from '@vuelidate/core'
import {GetInvMoveLineResp, WmInvMoveLine} from '@njt/wms/defs/inventory/invmove.d'
import {WmWhLite} from '@njt/wms/defs/basic/wh'
import {CodeLineForDropdown, MfLite} from '@njt/foundation/helper/dropdownlist.d'
import {WmZoneLite} from '@njt/wms/defs/basic/zone'
import {ColumnInfo} from '@njt/foundation/defs/comm'
import {useLineDetailHelper} from '@njt/foundation/hooks/lineDetailHelper'
import _ from 'lodash'
import {WmInvLocForList} from '@njt/wms/defs/inventory/invloc'
import {MhlInvMove, MhlInvMoveExt} from 'src/defs/invMove'
// 当前正在显示的tab
let showingTabPanel = ref('invMove')

interface PropsDef {
  // 页面选项，字段选项
  maxUploadSize?: number
  // 启用图片上传
  enableWmsSkuPicture?: boolean
  // 启用附件打包下载
  enableAccessoryPackDownload?: boolean
}

let props = withDefaults(defineProps<PropsDef>(), {
  maxUploadSize: 30,
  enableWmsSkuPicture: false,
  enableAccessoryPackDownload: false
})

const pageTitle = '移库单'
useTitleHelper(pageTitle)
// 错误信息内容
let serverErrorMessage = ref('')
// 数据加载状态
let loadingState = ref(false)
// 详情提交状态
let modelSubmittingState = ref(false)
let columnsInfoInvMoveLine: ColumnInfo[] = [
  {
    name: 'operation',
    label: '操作',
    field: 'operation',
    align: 'left',
    defOrder: 1,
    defVisible: true
  },
  {
    label: '移库单明细ID',
    name: 'moveLineId',
    field: 'moveLineId',
    align: 'left',
    defOrder: 2,
    sortable: true,
    defVisible: true
  },
  {
    label: '主档ID',
    name: 'moveId',
    field: 'moveId',
    align: 'left',
    defOrder: 3,
    defVisible: false
  },
  {
    label: '库存ID',
    name: 'invLocId',
    field: 'invLocId',
    align: 'left',
    defOrder: 4,
    defVisible: true
  },
  {
    label: '料号ID',
    name: 'skuId',
    field: 'skuId',
    align: 'left',
    defOrder: 5,
    defVisible: false
  },
  {
    label: '料号',
    name: 'sku',
    field: 'sku',
    align: 'left',
    defOrder: 6,
    sortable: true,
    defVisible: true
  },
  {
    label: '品名',
    name: 'skuName',
    field: 'skuName',
    align: 'left',
    defOrder: 7,
    defVisible: true
  },
  {
    label: '英文品名',
    name: 'skuNameE',
    field: 'skuNameE',
    align: 'left',
    defOrder: 8,
    defVisible: true
  },
  {
    label: '规格型号',
    name: 'spec',
    field: 'spec',
    align: 'left',
    defOrder: 9,
    defVisible: true
  },
  {
    label: '批号',
    name: 'lot',
    field: 'lot',
    align: 'left',
    defOrder: 10,
    sortable: true,
    defVisible: true
  },
  {
    label: '数量',
    name: 'qty',
    field: 'qty',
    align: 'left',
    defOrder: 11,
    defVisible: true
  },
  {
    label: '来源储位ID',
    name: 'fLocId',
    field: 'fLocId',
    align: 'left',
    defOrder: 12,
    defVisible: false
  },
  {
    label: '来源储位编号',
    name: 'fLoc',
    field: 'fLoc',
    align: 'left',
    defOrder: 13,
    sortable: true,
    defVisible: true
  },
  {
    label: '来源栈板',
    name: 'fLpn',
    field: 'fLpn',
    align: 'left',
    defOrder: 14,
    defVisible: true
  },
  {
    label: '目标储位ID',
    name: 'tLocId',
    field: 'tLocId',
    align: 'left',
    defOrder: 15,
    defVisible: false
  },
  {
    label: '目标储位编号',
    name: 'tLoc',
    field: 'tLoc',
    align: 'left',
    defOrder: 16,
    defVisible: true
  },
  {
    label: '目标栈板',
    name: 'tLpn',
    field: 'tLpn',
    align: 'left',
    defOrder: 17,
    defVisible: true
  },
  {
    label: '描述',
    name: 'descriptions',
    field: 'descriptions',
    align: 'left',
    defOrder: 18,
    defVisible: true
  },
  {
    label: '是否移库完成',
    name: 'isMoved',
    field: 'isMoved',
    align: 'left',
    defOrder: 19,
    defVisible: true
  },
  {
    label: '操作日期',
    name: 'operateDt',
    field: 'operateDt',
    align: 'left',
    defOrder: 20,
    defVisible: true,
    format: (value: string) => $f.fmt.dtFmtFull(value)
  },
  {
    label: '操作人',
    name: 'operateP',
    field: 'operateP',
    align: 'left',
    defOrder: 21,
    defVisible: true
  }
]
// 分页参数
let $d = reactive({
  paginationMoveLine: {
    // 页码
    page: 1,
    // 每页多少条
    rowsPerPage: 40,
    // 是否倒序
    descending: false,
    // 按什么排序
    sortBy: 'moveLineId'
  },
  form: {
    mhlInvMoveExt: {} as MhlInvMoveExt
  } as MhlInvMove,
  zoneDropdownList: [] as WmZoneLite[],
  whDropdownList: [] as WmWhLite[],
  storerDropdownList: [] as MfLite[],
  docTypeDropdownList: [] as CodeLineForDropdown[],
  selectedInvMoveLines: [] as WmInvMoveLine[],
  moveStateDropdownList: [
    {label: '初始', value: '0'},
    {label: '已审核', value: '1'},
    {label: '移库中', value: '5'},
    {label: '移库完成', value: '9'},
    {label: '已取消', value: 'C'}
  ],
  visibleColumnsInvMoveLine: [] as string[],
  //目标储位下拉
  locDropdownList: [] as Record<string, string | number>[]
})
let supplierList = ['亚利', '苏州雅利', '园区', 'XXD']
let submitingState = ref(false)
let moveDetailHasLines = ref(false)
// 主档数据
const loadModelData = function () {
  serverErrorMessage.value = ''
  loadingState.value = true
  $f.axios
    .get<MhlInvMove>('/project/mhlbc/inv/inventory/get-inv-move-by-id/' + detailInfo.itemId + '?withDetail=true')
    .then((resp) => {
      resp.data.expectedDt = $f.fmt.dtFmtDateOnly(resp.data.expectedDt)
      resp.data.confirmDt = $f.fmt.dtFmtFullWithMSec(resp.data.confirmDt as string)
      $d.selectedInvMoveLines = []
      if (resp.data.mhlLines.length > 0) {
        moveDetailHasLines.value = true
      }
      $d.form = resp.data
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingState.value = false
    })
}
// 主档帮助方法
const {
  detailInfo,
  detailStatus,
  detailNav,
  dlAssist
} = useDetailHelper('/wms/inv/move',
  null,
  null,
  '/wms/inv/move',
  '/wms/inv/move/detail',
  '/wms/inv/move/create',
  '/wms/inv/move/edit',
  loadModelData,
  serverErrorMessage
)
// 主档新建/编辑确定
const doSubmit = function () {
  serverErrorMessage.value = ''
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        let formParam = $f.misc.makeSimpleFormObj($d.form)
        if (isCreateMode.value) {
          submitingState.value = true
          $f.axios
            .post('/project/mhlbc/inv/inventory/create-inv-move', formParam)
            .then(() => {
              detailNav.goBackToList()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              submitingState.value = false
            })
        } else if (isEditMode.value) {
          delete $d.form.confirmDt
          submitingState.value = true
          $f.axios
            .post('/project/mhlbc/inv/inventory/update-inv-move', $d.form)
            .then(() => {
              detailNav.doneEdit()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              submitingState.value = false
            })
        }
      }
    })
}

const deleteInvMove = function () {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要删除该移库单吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/project/mhlbc/inv/inventory/delete-inv-moves', [detailInfo.itemId])
        .then(() => {
          $f.ui.closeMsgBox()
          detailNav.goBackToList()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '删除失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

const checkFn = function () {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要通过该移库单吗?',
    icon: 'Question',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/wms/inv/inventory/confirm-inv-move/' + detailInfo.itemId)
        .then(() => {
          $f.ui.closeMsgBox()
          loadModelData()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '删除失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

const cancelFn = function () {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要取消该移库单吗?',
    icon: 'Question',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/wms/inv/inventory/cancel-inv-move/' + detailInfo.itemId)
        .then(() => {
          $f.ui.closeMsgBox()
          loadModelData()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '删除失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

const printMoveInv = function () {
  $f.nw.downloadFileWithAuth(
    $f.appCfg.apiBaseUrl + '/wms/inv/inventory/print-move-inv/' + detailInfo.itemId,
    '',
    true
  )
}

const validators = $f.validators
// 主档验证相关
const rules = {
  whId: {
    required: validators.required
  },
  storerId: {
    required: validators.required
  },
  fZoneId: {
    required: validators.required
  },
  tZoneId: {
    required: validators.required
  },
  expectedDt: {
    required: validators.required
  },
  reason: {
    required: validators.required
  },
  docType: {
    required: validators.required
  }
}

const v$ = useVuelidate(rules, computed(() => $d.form), {$autoDirty: true, $scope: false})

let lineLoadingState = ref(false)
let serverErrorMessageModelData = ref('')
const loadLineModelData = function () {
  lineLoadingState.value = true
  $f.axios
    .get<GetInvMoveLineResp>('/wms/inv/inventory/get-inv-moveline-by-id/' + String(ldhModelData.lineDetailInfo.lineItemId))
    .then((resp) => {
      ldhModelData.lineDetailInfo.lineForm = resp.data
      $d.locDropdownList = [{locId: resp.data.tLocId, loc: resp.data.tLoc as string}]
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      lineLoadingState.value = false
    })
}

const {
  isViewMode,
  isCreateMode,
  isEditMode,
  isCreateOrEditMode,
  isViewOrEditMode,
  pageSubTitle
} = detailStatus

let ldhModelData = useLineDetailHelper(
  '移库单明细',
  'invMoveLineList',
  'invMoveLineDetail',
  null,
  loadLineModelData,
  showingTabPanel,
  serverErrorMessageModelData,
  () => {
    v$model.value.$reset()
  }
)


const ldsModelData = ldhModelData.lineDetailStatus

let colsInfoSaved = dlAssist.loadDetailColOptions('invMoveLineList', columnsInfoInvMoveLine)
columnsInfoInvMoveLine = colsInfoSaved[0]
$d.visibleColumnsInvMoveLine = colsInfoSaved[1]
$d.paginationMoveLine.rowsPerPage = dlAssist.loadDetailPageSize('invMoveLineList')

const createInvMoveLine = function () {
  ldhModelData.lineDetailNav.goCreateLine({
    moveId: $d.form.moveId,
    skuId: null,
    sku: null,
    skuName: null,
    skuNameE: null,
    spec: null,
    lot: null,
    qty: null,
    fLocId: null,
    fLoc: null,
    fLpn: null,
    tLocId: null,
    tLoc: null,
    tLpn: null,
    descriptions: null,
    isMoved: false,
    qtyAvailable: 0
  })
}

const doSubmitInvMoveLine = function () {
  serverErrorMessageModelData.value = ''
  void v$model.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        let lineForm = $f.misc.removePropertyOfNull(ldhModelData.lineDetailInfo.lineForm)
        if (ldsModelData.isLineCreateMode.value) {
          modelSubmittingState.value = true
          $f.axios
            .post('/project/mhlbc/inv/inventory/create-inv-moveline', lineForm)
            .then(() => {
              ldhModelData.lineDetailNav.backToListTab()
              loadModelData()
            })
            .catch((err) => {
              serverErrorMessageModelData.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              modelSubmittingState.value = false
            })
        } else if (ldsModelData.isLineEditMode.value) {
          modelSubmittingState.value = true
          $f.axios
            .post('/project/mhlbc/inv/inventory/update-inv-moveline', lineForm)
            .then(() => {
              ldhModelData.lineDetailNav.doneLineEdit()
              loadModelData()
            })
            .catch((err) => {
              serverErrorMessageModelData.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              modelSubmittingState.value = false
            })
        }
      }
    })
}

// 删除明细多个
const onDeleteInvMoveLines = function () {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要删除选中移库单明细吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/wms/inv/inventory/delete-inv-movelines', _.map($d.selectedInvMoveLines, 'moveLineId'))
        .then(() => {
          $f.ui.closeMsgBox()
          $d.selectedInvMoveLines = []
          loadModelData()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '删除失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

const onDeleteInvMoveLine = function (itemId: string | number | null) {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要删除该移库单细吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/wms/inv/inventory/delete-inv-movelines', [itemId])
        .then(() => {
          $f.ui.closeMsgBox()
          ldhModelData.lineDetailNav.backToListTab()
          loadModelData()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '删除失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}
// 仓库选择变更
const onWhChanged = function (value: number) {
  $d.form.fZoneId = null
  $d.form.tZoneId = null
  void $f.lst.getZoneSimpleList(value)
    .then((resp) => {
      $d.zoneDropdownList = resp.zones
    })
  v$.value.$reset()
}

const onInvLocSelected = function (locInfo: WmInvLocForList) {
  ldhModelData.lineDetailInfo.lineForm.invLocId = locInfo?.invLocId
  ldhModelData.lineDetailInfo.lineForm.sku = locInfo?.sku
  ldhModelData.lineDetailInfo.lineForm.skuId = locInfo?.skuId
  ldhModelData.lineDetailInfo.lineForm.skuName = locInfo?.skuName
  ldhModelData.lineDetailInfo.lineForm.skuNameE = locInfo?.skuNameE
  ldhModelData.lineDetailInfo.lineForm.lot = locInfo?.lot
  ldhModelData.lineDetailInfo.lineForm.fLocId = locInfo?.locId
  ldhModelData.lineDetailInfo.lineForm.fLoc = locInfo?.loc
  ldhModelData.lineDetailInfo.lineForm.fLpn = locInfo?.lpn
  ldhModelData.lineDetailInfo.lineForm.qtyAvailable = locInfo?.qtyAvailable
}

// 详情验证相关
const rulesModel = {
  invLocId: {
    required: validators.required
  },
  qty: {
    required: validators.required,
    int32: validators.int32,
    greaterThan: validators.greaterThan(0),
    lessEqualThan: validators.lessEqualThan(computed(() => ((ldhModelData.lineDetailInfo.lineForm as WmInvLocForList).qtyAvailable)))
  },
  tLocId: {
    required: validators.required
  },
  tLpn: {
    required: validators.required
  }
}

const v$model = useVuelidate(rulesModel, computed(() => ldhModelData.lineDetailInfo.lineForm as any), {$autoDirty: true, $scope: false})

// 获取仓库下拉数据源
void $f.lst.getWmWhSimpleList()
  .then((resp) => {
    $d.whDropdownList = resp
  })
//获取货主下拉数据源
void $f.lst.getMfSimpleList({isStorer: true})
  .then((resp) => {
    $d.storerDropdownList = resp.mfLiteList
  })

void $f.lst.getZoneSimpleList(null)
  .then((resp) => {
    $d.zoneDropdownList = resp.zones
  })

void $f.lst.getCodeForDropdown('InvMoveDocType')
  .then((resp) => {
    $d.docTypeDropdownList = resp
  })

const fx = $f
const e$ = $f.getFieldErrStr
</script>
